package com.baiyinet.ui.player;

import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alivc.player.AliVcMediaPlayer;
import com.alivc.player.MediaPlayer;
import com.baiyinet.BuildConfig;
import com.baiyinet.MyApp;
import com.baiyinet.R;
import com.baiyinet.biz.CurrentUser;
import com.baiyinet.biz.PageStatus;
import com.baiyinet.di.DaggerScope;
import com.baiyinet.di.Injector;
import com.baiyinet.rest.ApiHelper;
import com.baiyinet.rest.ApiResult;
import com.baiyinet.rest.MessageInfo;
import com.baiyinet.rest.PlayerDetail;
import com.baiyinet.util.IntentUtils;
import com.baiyinet.util.ShareUtils;
import com.baiyinet.util.Utils;
import com.bumptech.glide.Glide;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import rx.Subscriber;

/**
 * Created by developer on 18-1-30.
 */

@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(AliyunPlayerActivity.class)
@EActivity(R.layout.activity_player)
public class AliyunPlayerActivity extends AppCompatActivity {

    @ViewById(R.id.player_surface)
    SurfaceView mSurfaceView;
    @ViewById(R.id.player_layout_common)
    RelativeLayout mLayoutCommon;
    @ViewById(R.id.player_layout_list)
    RelativeLayout mLayoutList;
    @ViewById(R.id.player_list)
    RecyclerView mRecyclerView;
    @ViewById(R.id.player_iv_icon)
    ImageView mImageIcon;
    @ViewById(R.id.player_tv_title)
    TextView mTextViewTitle;
    @ViewById(R.id.player_layout_bottom)
    RelativeLayout mLayoutBottom;
    @ViewById(R.id.player_layout_send_msg)
    LinearLayout mLayoutSend;
    @ViewById(R.id.player_et_send_msg)
    EditText mEditSend;
    @ViewById(R.id.player_layout_group)
    LinearLayout mLayoutGroup;
    @ViewById(R.id.player_layout_scroll)
    ScrollView mScrollView;


    private String mUrl = "";
//    private String mUrl = "rtmp://5088.pptzb.com/1/4?auth_key=1519897390710-0-0-1d92a0f329ba173a08b18288c8b61210";
    private AliVcMediaPlayer mPlayer;

    @Inject
    ApiHelper mApiHelper;
    @Inject
    CurrentUser mCurrentUser;
    private int mRadioId = -1;
    private ArrayList<MessageInfo.Msg> mMsgList;
    private MyHandler mHandler;
    private PlayerDetail mPlayerDetail;

    @AfterInject
    void initDI() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        Injector.initAliyunPlayerActivityComponent().inject(this);
        mMsgList = new ArrayList<>();
        mHandler = new MyHandler(this);

        Intent intent = getIntent();
        if (intent != null && intent.getExtras() != null) {
            String url = intent.getStringExtra("url");
            String[] split = url.split("&");
            if (split.length > 2) {
                String radioIdStr = split[1];
                String radioUrlStr = split[2];
                mRadioId = Integer.valueOf(radioIdStr.substring(radioIdStr.indexOf("=") + 1));
                mUrl = radioUrlStr.substring(radioUrlStr.indexOf("=") + 1);

            }
        }

        mApiHelper.getDetail(new GetDetailSubscriber(), mRadioId);
    }

    @AfterViews
    void initView() {

        mSurfaceView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mLayoutCommon.getVisibility() == View.GONE) {
                    mLayoutCommon.setVisibility(View.VISIBLE);
                    mLayoutList.setVisibility(View.GONE);
                }else {
                    if (mLayoutBottom.getVisibility() == View.GONE) {
                        mLayoutBottom.setVisibility(View.VISIBLE);
                        mLayoutSend.setVisibility(View.GONE);
                        Utils.UI.hideInputMethod(mEditSend);
                    }
                }

            }
        });

        //创建播放器的实例
        mPlayer = new AliVcMediaPlayer(this, mSurfaceView);
        mPlayer.setVideoScalingMode(MediaPlayer.VideoScalingMode.VIDEO_SCALING_MODE_SCALE_TO_FIT);
        mPlayer.setMaxBufferDuration(8000);

        if (mPlayer != null && !TextUtils.isEmpty(mUrl)) {
            mPlayer.prepareAndPlay(mUrl);
        }

        mPlayer.setPreparedListener(new MediaPlayer.MediaPlayerPreparedListener() {
            @Override
            public void onPrepared() {
                //准备完成时触发
            }
        });

        mPlayer.setVideoScalingMode(MediaPlayer.VideoScalingMode.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
        mPlayer.setFrameInfoListener(new MediaPlayer.MediaPlayerFrameInfoListener() {
            @Override
            public void onFrameInfoListener() {
                //首帧显示时触发
//                Utils.UI.showToastShort("播放开始");
            }
        });

        mPlayer.setErrorListener(new MediaPlayer.MediaPlayerErrorListener() {
            @Override
            public void onError(int i, String msg) {
                //错误发生时触发，错误码见接口文档
                Utils.UI.showToastShort("播放失败");
            }
        });

        mSurfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                holder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
                holder.setKeepScreenOn(true);
                if (mPlayer != null) {
                    mPlayer.setVideoSurface(mSurfaceView.getHolder().getSurface());
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                if (mPlayer != null)
                    mPlayer.setSurfaceChanged();
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {

            }
        });

    }

    private void initDetail(final PlayerDetail playerDetail) {
        mPlayerDetail = playerDetail;

        String imageUrl = playerDetail.ImageUrl;

        if (!TextUtils.isEmpty(imageUrl)) {

            if (imageUrl.contains(",")) {
                String[] split = imageUrl.split(",");
                if (split.length > 0) {
                    Glide
                            .with(this)
                            .load(BuildConfig.ENDPOINT + split[0])
                            .into(mImageIcon);
                }
            }else {
                Glide
                        .with(this)
                        .load(BuildConfig.ENDPOINT + imageUrl)
                        .into(mImageIcon);
            }
        }

        if (!TextUtils.isEmpty(playerDetail.Title)) {
            mTextViewTitle.setText(playerDetail.Title);
        }

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        MyAdapter myAdapter = new MyAdapter(playerDetail);
        mRecyclerView.setAdapter(myAdapter);
        myAdapter.setOnItemClickListener(new OnRecyclerItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                int id = playerDetail.ProductList.get(position).Id;
                String url = BuildConfig.ENDPOINT + "SDP/Product/DetailForCustomer/" + id + "?RadioId=" + mRadioId;
                PageStatus pageStatus = new PageStatus(url, true);
                pageStatus.toolbarUpButtonEnabled = true;
                pageStatus.toolbarBgColor = mCurrentUser.getToolbarBgColor();
                IntentUtils.toNewGeneralActivity(AliyunPlayerActivity.this, pageStatus);
            }
        });

    }

    private void invalidateMsg() {
        if (mRadioId != -1) {
            mApiHelper.readMessage(new ReadMessageSubscriber(), mRadioId, 1, 30);
        }
    }

    private LinearLayout initMsgView(MessageInfo.Msg msg) {
        TextView textView1 = new TextView(this);
        textView1.setTextSize(17);
        if (msg.Type == 1) {
            textView1.setTextColor(Color.YELLOW);
            textView1.setText(msg.Name + " : ");
        }else {
            textView1.setTextColor(Color.RED);
            textView1.setText("系统消息 : ");
        }

        TextView textView2 = new TextView(this);
        textView2.setTextSize(17);
        textView2.setTextColor(Color.WHITE);
        textView2.setText(msg.Content);

        LinearLayout layout = new LinearLayout(this);
        layout.setGravity(Gravity.CENTER);
        layout.setOrientation(LinearLayout.HORIZONTAL);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        layout.addView(textView1, params);
        layout.addView(textView2, params);

        return layout;

    }

    private void initMsg(MessageInfo messageInfo) {
        mHandler.sendEmptyMessageDelayed(123, 2000);

        ArrayList<MessageInfo.Msg> data = (ArrayList<MessageInfo.Msg>) messageInfo.Data;
        Collections.reverse(data);
        if (mMsgList.size() == 0) {
            mLayoutGroup.removeAllViews();
            for (int i = 0; i < data.size(); i ++) {
                MessageInfo.Msg msg = data.get(i);
                initMsgView(msg);

                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                params.setMargins(0, Utils.UI.dip2px(10, this), 0, 0);
                mLayoutGroup.addView(initMsgView(msg), params);
                mMsgList.add(msg);
            }
        }else {
            ArrayList<MessageInfo.Msg> tempList = new ArrayList<>();
            tempList.addAll(data);

            for (MessageInfo.Msg msg : data) {
                for (MessageInfo.Msg msg1 : mMsgList) {
                    if (msg.Id == msg1.Id) {
                        tempList.remove(msg);
                    }
                }
            }

            int size = mMsgList.size();
            if (size < 30) {
                if (size + tempList.size() > 30) {
                    size = size + tempList.size() - 30;
                }else {
                    size = 0;
                }
            }else {
                size = tempList.size();
            }

            for (int i = 0; i < size; i ++) {
                mLayoutGroup.removeViewAt(i);
                mMsgList.remove(i);
            }

            for (int i = 0; i < tempList.size(); i ++) {
                MessageInfo.Msg msg = tempList.get(i);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                params.setMargins(0, Utils.UI.dip2px(10, this), 0, 0);
                mLayoutGroup.addView(initMsgView(msg), params);
                mMsgList.add(msg);
            }

        }

        mHandler.post(new Runnable() {
            @Override
            public void run() {
                mScrollView.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });

    }

    @Click(R.id.player_iv_bag)
    void showListLayout() {
        mLayoutCommon.setVisibility(View.GONE);
        mLayoutList.setVisibility(View.VISIBLE);
    }

    @Click(R.id.player_iv_close)
    void closePlayer() {
        finish();
    }

    @Click(R.id.player_iv_share)
    void shareRadio() {
        String shareUrl = BuildConfig.ENDPOINT + "SDP/AnchorRecord/Detail/" + mRadioId;

        if (mPlayerDetail != null) {
            ShareUtils.showSharePanel(this, mPlayerDetail.Title, mPlayerDetail.Description, shareUrl, BuildConfig.ENDPOINT + mPlayerDetail.ImageUrl);
        }
    }

    @Click(R.id.player_iv_chat)
    void showSendMsg() {
        mLayoutBottom.setVisibility(View.GONE);
        mLayoutSend.setVisibility(View.VISIBLE);
        Utils.UI.showInputMethod(mEditSend);
    }

    @Click(R.id.player_btn_send_msg)
    void sendMessage() {
        Utils.UI.hideInputMethod(mEditSend);
        String msg = mEditSend.getText().toString().trim();
        if (!TextUtils.isEmpty(msg)) {
            mApiHelper.addMessage(new AddMessageSubscriber(), mRadioId, msg);
        }


    }


    @Override
    protected void onPause() {
        super.onPause();
        if (mPlayer != null) {
            mPlayer.stop();
        }

        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mPlayer != null && !TextUtils.isEmpty(mUrl)) {
            mPlayer.prepareAndPlay(mUrl);
        }

        mHandler.sendEmptyMessage(123);
    }

    @Override
    protected void onDestroy() {
        if (mPlayer != null) {
            mPlayer.destroy();
        }
        mHandler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }

    private class MyAdapter extends RecyclerView.Adapter {

        private final ArrayList<PlayerDetail.Product> mProductList;
        OnRecyclerItemClickListener mOnRecyclerItemClickListener;

        public MyAdapter(PlayerDetail playerDetail) {
            mProductList = playerDetail.ProductList;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new MyViewHolder(View.inflate(AliyunPlayerActivity.this, R.layout.item_player_list, null));
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

            final PlayerDetail.Product product = mProductList.get(position);
            MyViewHolder myHolder = (MyViewHolder) holder;
            if (!TextUtils.isEmpty(product.ImageUrl)) {
                Glide
                        .with(AliyunPlayerActivity.this)
                        .load(BuildConfig.ENDPOINT + product.ImageUrl)
                        .into(myHolder.ivIcon);
            }

            myHolder.tvTitle.setText(product.Title);
            myHolder.tvPrice.setText("￥" + product.ShowPrice);
            myHolder.button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int id = product.Id;
                    String url = BuildConfig.ENDPOINT + "SDP/Product/DetailForCustomer/" + id + "?RadioId=" + mRadioId;
                    PageStatus pageStatus = new PageStatus(url, true);
                    pageStatus.toolbarUpButtonEnabled = true;
                    pageStatus.toolbarBgColor = mCurrentUser.getToolbarBgColor();
                    IntentUtils.toNewGeneralActivity(AliyunPlayerActivity.this, pageStatus);

                }
            });
        }

        @Override
        public int getItemCount() {
            return mProductList.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

            TextView tvTitle;
            TextView tvPrice;
            ImageView ivIcon;
            Button button;


            MyViewHolder(View itemView) {
                super(itemView);
                tvTitle = itemView.findViewById(R.id.item_player_tv_title);
                tvPrice = itemView.findViewById(R.id.item_player_tv_price);
                ivIcon = itemView.findViewById(R.id.item_player_img);
                button = itemView.findViewById(R.id.item_player_btn);
                itemView.setOnClickListener(this);
            }

            @Override
            public void onClick(View v) {
                mOnRecyclerItemClickListener.onItemClick(v, getAdapterPosition());
            }

        }

        public void setOnItemClickListener(OnRecyclerItemClickListener onItemClickListener) {
            mOnRecyclerItemClickListener = onItemClickListener;
        }
    }

    private interface OnRecyclerItemClickListener {
        void onItemClick(View view, int position);
    }

    private class GetDetailSubscriber extends Subscriber<PlayerDetail> {

        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {
            Utils.UI.showToastShort(e.toString());
        }

        @Override
        public void onNext(PlayerDetail playerDetail) {
            if (playerDetail != null && playerDetail.ProductList.size() > 0) {
                initDetail(playerDetail);
            }
        }
    }

    private class AddMessageSubscriber extends Subscriber<ApiResult> {

        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {
            Log.e("ALiyunPlayer", e.toString());
        }

        @Override
        public void onNext(ApiResult apiResult) {
            Toast.makeText(AliyunPlayerActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
            mEditSend.setText("");
            if (mLayoutSend.getVisibility() == View.VISIBLE) {
                mLayoutSend.setVisibility(View.GONE);
                mLayoutBottom.setVisibility(View.VISIBLE);

            }
        }
    }

    private class ReadMessageSubscriber extends Subscriber<MessageInfo> {

        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {
            Log.e("ALiyunPlayer", e.toString());
        }

        @Override
        public void onNext(MessageInfo messageInfo) {
            if (messageInfo != null && messageInfo.Total > 0) {
                initMsg(messageInfo);
            }
        }
    }

    public static class MyHandler extends Handler {

        WeakReference<AliyunPlayerActivity> weakReference;

        MyHandler(AliyunPlayerActivity activity) {
            weakReference = new WeakReference<AliyunPlayerActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            AliyunPlayerActivity activity = weakReference.get();
            if (activity != null) {

                if (msg.what == 123) {
                    activity.invalidateMsg();
                }
            }
        }
    }

}
